<template>
  <div class="inbound-list" v-loading="loading">
    <div class="page-header">
      <h2>入库管理</h2>
    </div>

    <div class="action-bar">
      <div class="left-actions">
        <el-button type="primary" icon="Plus" @click="handleAdd">新增</el-button>
        <el-button type="success" icon="Document" @click="exportExcel">导出</el-button>
      </div>
      <div class="right-actions">
        <el-input v-model="searchText" placeholder="请搜索" class="search-input" clearable @keyup.enter="reload">
          <template #append>
            <el-button icon="Search" @click="reload" />
          </template>
        </el-input>
        <el-button icon="Refresh" @click="reload" />
      </div>
    </div>

    <el-table :data="rows" border stripe v-loading="tableLoading">
      <el-table-column type="selection" width="55" />
      <el-table-column type="index" label="#" width="60" />
      <el-table-column prop="inboundOrderNumber" label="入库单号" width="160" />
      <el-table-column prop="inboundSubject" label="入库主题" min-width="220" />
      <el-table-column prop="inboundDate" label="入库日期" width="120">
        <template #default="{ row }">{{ formatDate(row.inboundDate) }}</template>
      </el-table-column>
      <el-table-column prop="inboundType" label="入库类型" width="120" />
      <el-table-column label="物品概要" min-width="180">
        <template #default>
          <el-tooltip content="遮阳帽 等10项" :show-after="500"><span>遮阳帽 等10项</span></el-tooltip>
        </template>
      </el-table-column>
      <el-table-column prop="warehouseName" label="入库仓库" width="140" />
      <el-table-column prop="inboundPersonnelName" label="入库人员" width="120" />
      <el-table-column prop="totalQuantity" label="入库数量" width="100" />
      <el-table-column label="操作" width="100" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" link @click="viewDetail(row.id)">查看</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <div class="pagination-info">共 {{ total }} 项数据</div>
      <el-pagination
        v-model:current-page="pageIndex"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[5,10,20,50]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="onSizeChange"
        @current-change="onPageChange"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { inboundApi, type InboundListRow } from '@/api/inboundApi'
import * as XLSX from 'xlsx'

const router = useRouter()
const loading = ref(false)
const tableLoading = ref(false)
const rows = ref<InboundListRow[]>([])
const pageIndex = ref(1)
const pageSize = ref(10)
const total = ref(0)
const searchText = ref('')

onMounted(() => reload())

const reload = async () => {
  try {
    tableLoading.value = true
    console.log('开始加载入库列表数据...')
    console.log('请求参数:', { pageIndex: pageIndex.value, pageSize: pageSize.value })
    
    const res = await inboundApi.list(pageIndex.value, pageSize.value)
    console.log('入库列表API响应:', res)
    
    if (res.code === 200) {
      console.log('API调用成功，数据:', res.data)
      console.log('分页数据:', res.data.pageData)
      console.log('总条数:', res.data.totalCount)
      
      // 确保数据是数组
      const pageData = Array.isArray(res.data.pageData) ? res.data.pageData : []
      rows.value = pageData
      total.value = res.data.totalCount || 0
      
      console.log('设置到组件的数据:', rows.value)
      console.log('设置的总条数:', total.value)
      console.log('数据长度:', rows.value.length)
      
      // 如果数据为空，显示提示
      if (pageData.length === 0) {
        console.warn('API返回的数据为空')
        ElMessage.warning('暂无数据')
      }
    } else {
      console.error('API返回错误:', res.message)
      ElMessage.error(res.message || '加载失败')
    }
  } catch (error) {
    console.error('加载入库列表失败:', error)
    ElMessage.error('加载失败: ' + (error as Error).message)
  } finally {
    tableLoading.value = false
  }
}

const handleAdd = () => {
  router.push('/InboundCreate')
}

const viewDetail = (id: number) => router.push(`/InboundDetail/${id}`)
const onSizeChange = (s: number) => { pageSize.value = s; pageIndex.value = 1; reload() }
const onPageChange = (p: number) => { pageIndex.value = p; reload() }

const exportExcel = () => {
  const data = rows.value.map((r, i) => ({
    序号: i + 1,
    入库单号: r.inboundOrderNumber,
    入库主题: r.inboundSubject,
    入库日期: formatDate(r.inboundDate),
    入库类型: r.inboundType,
    入库仓库: r.warehouseName,
    入库人员: r.inboundPersonnelName,
    入库数量: r.totalQuantity,
    入库金额: r.totalAmount
  }))
  const ws = XLSX.utils.json_to_sheet(data)
  const wb = XLSX.utils.book_new()
  XLSX.utils.book_append_sheet(wb, ws, '入库列表')
  const ts = new Date().toISOString().slice(0,19).replace(/[:T]/g,'-')
  XLSX.writeFile(wb, `入库列表-${ts}.xlsx`)
}

const formatDate = (d: string) => new Date(d).toLocaleDateString('zh-CN')
</script>

<style scoped>
.inbound-list { padding: 20px; }
.page-header { margin-bottom: 16px; }
.action-bar { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; padding: 16px; background: #f5f7fa; border-radius: 4px; }
.left-actions { display: flex; gap: 10px; }
.right-actions { display: flex; align-items: center; gap: 10px; }
.search-input { width: 300px; }
.pagination-container { display: flex; justify-content: space-between; align-items: center; margin-top: 20px; padding: 16px; background: #f5f7fa; border-radius: 4px; }
.pagination-info { color: #606266; font-size: 14px; }
</style> 